<template>
	<view class="diaryContent" style="min-height: calc(100vh);">
		<view class="date">
			<text class="day">{{ date[0] }}</text>
			<text class="year">{{ date[1] }}</text>
			<text class="year">.</text>
			<text class="year">{{ date[2] }}</text>
		</view>
		<view class="diaryBox">
			<view class="diaryImgBox" @click="getPhoto">
				<auto-image class="diaryImg" :src="img" style="min-height: 447rpx;"></auto-image>
				<view class="diaryImgIcon">
					<image src="//mall-rongchuang.oss-cn-beijing.aliyuncs.com/guixin_miniProgram/img/select_pic.png" style="width: 48rpx;height: 48rpx;"></image>
					<text style="font-size: 28rpx;line-height: 40rpx;margin-top: 12rpx;">点击更改图片</text>
				</view>
			</view>
			<little-text
				v-if="beautifulDiary.photographer || alwaysShowPhotoGrapher"
				class="diaryFooter"
				content="摄影"
				:disabled="photoDisabled"
				v-model="beautifulDiary.photographer"
			/>
			<view class="diary-title">
				<textarea class="big-text" :maxlength="200" placeholder="请输入美好日记" :auto-focus="true" :style="{ height: bigTextHeight + 'rpx' }" focus v-model="beautifulDiary.diaryContent" @input="beautifulDiaryContentChange"></textarea>
				<big-text
					hideText
					class="diaryText"
					:height.sync="bigTextHeight"
					:maxLength="200"
					alwaysShowTips
					v-model="beautifulDiary.diaryContent"
				></big-text>
			</view>
			<sign-name class="diary-user-name" v-model="beautifulDiary.userName" :disabled="userNameDisabled"></sign-name>
		</view>
		<view class="buttons">
			<button class="diaryButton" form-type="submit" @click="release" :disabled="disabled">
				<image src="//mall-rongchuang.oss-cn-beijing.aliyuncs.com/guixin_miniProgram/img/send_msg.png" class="diaryImgButtonIcon"></image>
				发布
			</button>
		</view>
		<!-- 发布 -->
		<poster v-if="showPoster" ref="poster" :params.sync="poster" @share="showShare = true" @close="showPoster = false" :dirayId="beautifulDiary.diaryId"></poster>
		<image-cropper :src.sync="tempFilePath" :visible.sync="visible" @confirm="confirm" @cancel="cancel"></image-cropper>
		<uni-popup-slient ref="slient" :endTime="endTime"></uni-popup-slient>
		<loading ref="loading"></loading>
	</view>
</template>
<script>
import { mapState } from 'vuex';
import http, { uploadImages } from '../../common/request.js';
import { getResolvePath, getCommonShareInfo } from '../../common/utils.js';
import uniIcons from '@/components/uni-icons/uni-icons.vue';
import bridgeApi from '../../common/rayBridgeSDK.js';
import uniPopupSlient from '@/components/uni-popup/uni-popup-dialog-silent.vue';
import AutoImage from '@/components/uni-image/uni-image.vue';
import BigText from '../components/big-text.vue';
import LittleText from '../components/little-text.vue';
import SignName from '../components/sign-name.vue';
import ImageCropper from '@/components/uni-image/cropper.vue';
import Poster from '@/components/ray-poster/poster.vue';
import Loading from '@/components/notice/loading.vue';

export default {
	components: {
		uniIcons,
		uniPopupSlient,
		Poster,
		ImageCropper,
		AutoImage,
		BigText,
		LittleText,
		SignName,
		Loading
	},
	onLoad(params) {
		this.diaryId = params.diaryId || '';
		uni.loadFontFace({
			family: 'din',
			source: 'url("https://mall-rongchuang.oss-cn-beijing.aliyuncs.com/guixin_miniProgram/fonts/PTDINCondensedCyrillic.ttf")',
			success() {}
		});
	},
	watch: {
		visible(val) {
			if (val) {
				this.showText = false;
			} else {
				this.showText = true;
			}
		},
		showPoster(val) {
			if (val) {
				this.showText = false;
			} else {
				this.showText = true;
			}
		}
	},
	data() {
		// 获取当前日期
		var myDate = new Date().toDateString().split(' ');
		const date = [myDate[2], myDate[1], myDate[3]];
		return {
			bigTextHeight: 46,
			date,
			diaryId: '',
			photoDisabled: true,
			alwaysShowPhotoGrapher: false,
			userNameDisabled: true,
			showText: true,
			visible: false,
			tempFilePath: '',
			cropFilePath: '',
			showPoster: false,
			poster: {
				//主板版海报
				date,
				path: getResolvePath({ go: '/interaction/diary/index' }),
				// path: getResolvePath({go: '/interaction/diary/view'}),
				logoUrl: '',
				imageUrl: '',
				title: '',
				codeUrl: '',
				photoGrapher: '',
				userName: ''
			},
			cusList: {},
			diaryImg: '',
			diaryWord: '',
			// 日记
			beautifulDiary: {},
			diaryContent: '',
			percent: 0,
			loading: false,
			disabled: false,
			fileIds: [],
			img: '',
			endTime: ''
		};
	},
	computed: {
		...mapState({ userInfo: state => state.userInfo })
	},
	async onShareAppMessage(res) {
		if (res.from === 'menu') {
			return getCommonShareInfo();
		} else {
			const imageUrl = await this.$refs.poster.getSharePhoto();
			return {
				title: this.beautifulDiary.diaryContent,
				path: this.poster.path,
				imageUrl
			};
		}
	},
	mounted() {
		this.getData();
		setTimeout(r => {
			this.autoFocus = true;
		}, 1000);
	},
	methods: {
		toPage(value) {
			http('/api/duiba/getNoLoginUrl?credits=0&redirect=' + value, { method: 'GET' }).then(result => {
				if (result.code == 200) {
					// #ifdef H5
					location.href = result.data;
					// #endif
					// #ifdef MP-WEIXIN
					uni.navigateTo({
						url: '../../home/web_view?url=' + encodeURIComponent(result.data),
						animationType: 'pop-in',
						animationDuration: 200
					});
					// #endif
				}
			});
		},
		getData() {
			http('/api/cusBeautifulDiary/appIndexGetList', { method: 'GET', data: { cusDiaryId: this.diaryId } }).then(result => {
				this.beautifulDiary = result.data;
				this.img = result.data.imgUrl;
			});
		},
		//发布
		release: function(e) {
			if (this.beautifulDiary.diaryContent === '') {
				uni.showToast({
					title: '请输入美好日记内容！',
					icon: 'none'
				});
				return;
			}
			this.disabled = true;
			http('/api/cusUserInfo/getUserStatus/' + this.userInfo.userId, { data: {}, method: 'GET' })
				.then(result => {
					if (result.code == '200') {
						//  0 正常 1 禁言 2 停用
						if (!result.data) {
							this.dirayFb();
						} else {
							this.$refs.slient.open();
							this.endTime = result.forbiddenDate;
							this.disabled = false;
						}
					} else {
						this.disabled = false;
					}
				})
				.catch(r => {
					this.disabled = false;
				});
		},
		dirayFb() {
			http('/api/cusBeautifulDiary/publish', {
				method: 'POST',
				data: {
					diaryId: this.beautifulDiary.diaryId,
					fileIds: this.fileIds, //从文件服务器中获取返回来的imgId
					diaryContent: this.beautifulDiary.diaryContent,
					imgUrl: this.beautifulDiary.imgUrl,
					photographer: this.beautifulDiary.photographer,
					author: this.beautifulDiary.userName
				}
			})
				.then(result => {
					if (result.code == '200') {
						this.poster.path = getResolvePath({ go: '/interaction/diary/index?diaryId=' + result.msg });
						// this.poster.path = getResolvePath({ go: '/interaction/diary/view?diaryId=' + result.msg});
						http('/api/cusBeautifulDiary/shareInfo/' + result.msg, { method: 'GET' }).then(result => {
							const { diaryContent: title, imgUrl: imageUrl, userName, qrCodeImgUrl: codeUrl, logoImgUrl: logoUrl, photographer: photoGrapher } = result.data || {};
							Object.assign(this.poster, { title, userName, imageUrl, codeUrl, logoUrl, photoGrapher });
							uni.showToast({
								title: '发布成功，可前往美好日记查看！',
								icon: 'none',
								duration: 1000
							});
							setTimeout(r => {
								this.showPoster = true;
							}, 1000);
							setTimeout(r => {
								this.disabled = false;
							}, 2000);
						});
					} else {
						this.disabled = false;
					}
				})
				.catch(r => {
					this.disabled = false;
				});
		},
		// 获取图片
		getPhoto(e) {
			// #ifdef H5
			window.showLoading = () => {
				this.$refs.loading.show();
			};
			bridgeApi.chooseImage().then(res => {
				window.showLoading = undefined;
				this.$refs.loading.close();
				const files = [];
				for (let item of res) {
					files.push('data:image/png;base64,' + item.url);
				}
				this.setCropperImage(files);
			});
			// #endif
			// #ifdef MP-WEIXIN
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: res => {
					this.setCropperImage(res.tempFilePaths);
				}
			});
			// #endif
		},
		setCropperImage(list) {
			this.tempFilePath = list[0];
			this.visible = true;
			this.photoDisabled = false;
			this.alwaysShowPhotoGrapher = true;
			this.beautifulDiary.photographer = this.userInfo.nickName;
		},
		beautifulDiaryContentChange() {
			this.userNameDisabled = false;
			this.beautifulDiary.userName = this.userInfo.nickName;
		},
		uploadImages(files) {
			this.$refs.loading.show('上传中');
			const list = [];
			for (let item of files) {
				list.push({
					name: 'file',
					uri: item
				});
			}
			uploadImages('/fastdfs/upload/multiUpload', {
				fileList: list
			})
				.then(result => {
					this.img = files[0];
					this.fileIds = JSON.parse(result[0]).data;
					this.$refs.loading.close();
					this.disabled = false;
				})
				.catch(e => {
					this.$refs.loading.close();
					// this.disabled = false;
					uni.showToast({
						title: '图片处理失败，请重新上传！',
						icon: 'none'
					})
				});
		},
		confirm(tempFilePath) {
			this.disabled = true;
			this.poster.imageUrl = tempFilePath;
			this.uploadImages([tempFilePath]);
		},
		cancel() {}
	}
};
</script>

<style scoped lang="scss">
@import './index.css';
.big-text {
	font-family: PingFangSC-Light, PingFang SC;
	color: #66645d;
	padding: 0;
	margin: 0;
	width: 100%;
	word-break: break-all;
	word-wrap: break-word;
	white-space: normal;
	min-height: 46rpx;
	font-size: 26rpx;
	line-height: 40rpx;
	font-weight: 300;
	font-family: PingFangSC-Light, PingFang SC;
}
</style>
